window.onload = function () {
  imgLocation("container","box")
}

function imgLocation(parent,content) {
  // 将parent下的所有content全部取出
  var cparent = document.getElementById(parent)
  var contentArr = cparent.getElementsByClassName(content);
  var imgWidth = contentArr[0].offsetWidth;
  var num = Math.floor(document.documentElement.clientWidth / imgWidth);
  cparent.style.cssText = "width:"+imgWidth*num+"px;margin:0 auto"
  // console.log(contentArr,num);

  var boxHeightArr = [];
  for (var i = 0; i < contentArr.length; i++) {
    if(i<num) {
      boxHeightArr[i] = contentArr[i].offsetHeight;
    }else {
      var minHeight = Math.min.apply(null,boxHeightArr);
      var minIndex = getMinHeight(boxHeightArr,minHeight);
      console.log(boxHeightArr,minIndex);
      contentArr[i].style.position = "absolute";
      contentArr[i].style.top = minHeight+"px";
      contentArr[i].style.left = contentArr[minIndex].offsetLeft+"px";
      boxHeightArr[minIndex] = boxHeightArr[minIndex]+contentArr[i].offsetHeight;//重新计算高度最小的图片
    }
  }


}
// 获取到最短的图片的位置，并将位置返回
function getMinHeight(boxHeightArr,minHeight) {
  for (var i in boxHeightArr) {
    if(boxHeightArr[i] == minHeight) {
      return i;
    }
  }
}




//
